use salvo::{handler, Request};
use validator::Validate;
use crate::domain::dto::{parser_to_json, rbatis_to_res, validation_to_json, PageRes, Res};
use crate::domain::dto::module_dto::{ModuleCreateRequest, ModulePageRequest, ModulePageResponse, ModuleUpdateRequest};
use crate::service::{module_service};

/// module_pages 数据模型分页查询
#[handler]
pub async fn module_pages(request: &mut Request) -> Res<PageRes<ModulePageResponse>> {
    let mut param = request.parse_json::<ModulePageRequest>()
        .await
        .map_err(|err| {
            tracing::error!("解析模型分页查询请求参数异常: {:?}", err);
            parser_to_json(err)
        })?;
    if param.page == None { param.page = Some(1) }
    if param.limit == None { param.limit = Some(10) }
    let res = module_service::module_pages(param).await;
    rbatis_to_res(res)
}

/// module_create 数据模型创建
#[handler]
pub async fn module_create(request: &mut Request) -> Res<bool> {
    let param = request.parse_json::<ModuleCreateRequest>()
        .await
        .map_err(|err| { parser_to_json(err) })?;

    // 验证
    let _ = param.validate().map_err(|err| validation_to_json(err))?;

    let res = module_service::module_create(param).await;
    rbatis_to_res(res)
}

/// module_update 数据模型更新
#[handler]
pub async fn module_update(request: &mut Request) -> Res<bool> {
    let param = request.parse_json::<ModuleUpdateRequest>()
        .await
        .map_err(|err| { parser_to_json(err) })?;

    // 验证
    let _ = param.validate().map_err(|err| validation_to_json(err))?;

    let res = module_service::module_update(param).await;
    rbatis_to_res(res)
}